package com.efast.dmom.mgmt.service.mes.impl;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.efast.cafe.framework.bean.ResultBean;
import com.efast.cafe.framework.exception.ServiceException;
import com.efast.cafe.framework.util.SpringWebUtils;
import com.efast.cafe.util.SpringUtils;
import com.efast.cafe.util.StringUtil;
import com.efast.cafe.util.date.DateUtils;
import com.efast.dmom.mgmt.bean.mes.LabelPrintDto;
import com.efast.dmom.mgmt.bean.mes.ProductExcuteDto;
import com.efast.dmom.mgmt.bean.mes.ReportDto;
import com.efast.dmom.mgmt.bean.mes.WorkOrderInfoDto;
import com.efast.dmom.mgmt.bean.mes.order.WorkOrderItem;
import com.efast.dmom.mgmt.dao.mes.TwBasLotDao;
import com.efast.dmom.mgmt.dao.mes.TwBasLotHistoryDao;
import com.efast.dmom.mgmt.dao.mes.TwBasLotRepairDao;
import com.efast.dmom.mgmt.dao.mes.TwBasWorkOrderDao;
import com.efast.dmom.mgmt.entity.les.TwInbTaskDetail;
import com.efast.dmom.mgmt.entity.les.TwOutbTaskDetail;
import com.efast.dmom.mgmt.entity.les.TwPacktranTaskDetail;
import com.efast.dmom.mgmt.entity.les.TwQualityTaskDetail;
import com.efast.dmom.mgmt.entity.master.TmBasLoc;
import com.efast.dmom.mgmt.entity.master.TmBasPackageSn;
import com.efast.dmom.mgmt.entity.master.TmBasPart;
import com.efast.dmom.mgmt.entity.master.TmBasPartSn;
import com.efast.dmom.mgmt.entity.master.TmBasSuppl;
import com.efast.dmom.mgmt.entity.master.TrBasRouteOperation;
import com.efast.dmom.mgmt.entity.mes.TeMesOutbound;
import com.efast.dmom.mgmt.entity.mes.TeProductInbound;
import com.efast.dmom.mgmt.entity.mes.TrBasPdPlRoute;
import com.efast.dmom.mgmt.entity.mes.TrBasProductCfgBi;
import com.efast.dmom.mgmt.entity.mes.TwBasLot;
import com.efast.dmom.mgmt.entity.mes.TwBasLotConsumpation;
import com.efast.dmom.mgmt.entity.mes.TwBasLotDataCollection;
import com.efast.dmom.mgmt.entity.mes.TwBasLotHistory;
import com.efast.dmom.mgmt.entity.mes.TwBasLotHoldHistory;
import com.efast.dmom.mgmt.entity.mes.TwBasLotRepair;
import com.efast.dmom.mgmt.entity.mes.TwBasLotTesting;
import com.efast.dmom.mgmt.entity.mes.TwBasWorkOrder;
import com.efast.dmom.mgmt.service.les.MaterialPullService;
import com.efast.dmom.mgmt.service.les.TwBasPackSkuQtyService;
import com.efast.dmom.mgmt.service.les.TwInvSkuLoctlService;
import com.efast.dmom.mgmt.service.master.TmBasLocService;
import com.efast.dmom.mgmt.service.master.TmBasPackageSnService;
import com.efast.dmom.mgmt.service.master.TmBasPartService;
import com.efast.dmom.mgmt.service.master.TmBasPartSnService;
import com.efast.dmom.mgmt.service.master.TmBasSupplService;
import com.efast.dmom.mgmt.service.master.TrBasRouteOperationService;
import com.efast.dmom.mgmt.service.mes.TeMesOutboundService;
import com.efast.dmom.mgmt.service.mes.TeProductInboundService;
import com.efast.dmom.mgmt.service.mes.TrBasPdPlRouteService;
import com.efast.dmom.mgmt.service.mes.TwBasLotConsumpationService;
import com.efast.dmom.mgmt.service.mes.TwBasLotDataCollectionService;
import com.efast.dmom.mgmt.service.mes.TwBasLotRepairService;
import com.efast.dmom.mgmt.service.mes.TwBasLotService;
import com.efast.dmom.mgmt.service.mes.TwBasLotTestingService;
import com.efast.dmom.mgmt.service.mes.TwBasWorkOrderService;
import com.efast.dmom.mgmt.service.mes.VinRuleService;
import com.efast.dmom.mgmt.utils.Assist;
import com.efast.dmom.mgmt.utils.MesConstant;
import com.efast.dmom.mgmt.utils.ObjectMapUtils;
import com.efast.dmom.mgmt.utils.PrintCardUtil;
import com.ibm.icu.text.SimpleDateFormat;
@Service
@Transactional
public class TwBasLotServiceImpl implements TwBasLotService{
	@Autowired
	private TwBasWorkOrderDao twBasWorkOrderDao;
    @Autowired
    private TwBasLotDao twBasLotDao;
    @Autowired
    private TwBasLotHistoryDao twBasLotHistoryDao;
    @Autowired
    private TwBasLotConsumpationService twBasLotConsumpationService;
    @Autowired
    private TwBasLotTestingService twBasLotTestingService;
    @Autowired
    private TwBasLotDataCollectionService twBasLotDataCollectionService;
    @Autowired
    private TmBasPartSnService tmBasPartSnService;
    @Autowired
    private TrBasRouteOperationService trBasRouteOperationService;
    @Autowired
    private TmBasPackageSnService tmBasPackageSnService;
    @Autowired
    private TrBasPdPlRouteService trBasPdPlRouteService;
    @Autowired
    private TwBasLotRepairDao twBasLotRepairDao;
    @Autowired
    private TeMesOutboundService teMesOutboundService;
    @Autowired
    private MaterialPullService materialPullService;
    @Autowired
    private TeProductInboundService teProductInboundService;
    @Autowired
    private TwBasWorkOrderService twBasWorkOrderService;
    @Autowired
    private TwBasLotRepairService twBasLotRepairService;
    @Autowired
    private TwInvSkuLoctlService twInvSkuLoctlService;
    @Autowired
    private TmBasPartService tmBasPartService;
    @Autowired
    private TmBasSupplService tmBasSupplService;
    @Autowired
    private TmBasLocService tmBasLocService;
	@Autowired
    private TwBasPackSkuQtyService twBasPackSkuQtyService;
	@Autowired
	private VinRuleService vinRuleService;
    @Override
    public long getTwBasLotRowCount(Assist assist){
        return twBasLotDao.getTwBasLotRowCount(assist);
    }
    @Override
    public List<TwBasLot> selectTwBasLot(Assist assist){
        return twBasLotDao.selectTwBasLot(assist);
    }
    @Override
    public TwBasLot selectTwBasLotByObj(TwBasLot obj){
        return twBasLotDao.selectTwBasLotByObj(obj);
    }
    @Override
    public TwBasLot selectTwBasLotById(Integer id){
        return twBasLotDao.selectTwBasLotById(id);
    }
    @Override
    public int insertTwBasLot(TwBasLot value){
        return twBasLotDao.insertTwBasLot(value);
    }
    @Override
    public int insertNonEmptyTwBasLot(TwBasLot value){
        return twBasLotDao.insertNonEmptyTwBasLot(value);
    }
    @Override
    public int insertTwBasLotByBatch(List<TwBasLot> value){
        return twBasLotDao.insertTwBasLotByBatch(value);
    }
    @Override
    public int deleteTwBasLotById(Integer id){
        return twBasLotDao.deleteTwBasLotById(id);
    }
    @Override
    public int deleteTwBasLot(Assist assist){
        return twBasLotDao.deleteTwBasLot(assist);
    }
    @Override
    public int updateTwBasLotById(TwBasLot enti){
        return twBasLotDao.updateTwBasLotById(enti);
    }
    @Override
    public int updateTwBasLot(TwBasLot value, Assist assist){
        return twBasLotDao.updateTwBasLot(value,assist);
    }
    @Override
    public int updateNonEmptyTwBasLotById(TwBasLot enti){
        return twBasLotDao.updateNonEmptyTwBasLotById(enti);
    }
    @Override
    public int updateNonEmptyTwBasLot(TwBasLot value, Assist assist){
        return twBasLotDao.updateNonEmptyTwBasLot(value,assist);
    }

    public TwBasLotDao getTwBasLotDao() {
        return this.twBasLotDao;
    }

    public void setTwBasLotDao(TwBasLotDao twBasLotDao) {
        this.twBasLotDao = twBasLotDao;
    }
    
    private final String VENDOR = "苏州益发特科技有限公司上海分公司";
    private final String ADDR = "上海市徐汇区钦州北路188号";
    
    @Override
	public String doSaveDatas(ProductExcuteDto dto) {
    		//保存或更新产品过程定义数据：包括物料消耗、检测、数据采集
    		String errorMsg = saveOrUpdateProcessDef(dto);
    		return errorMsg;
	}
	@Override
	public void dealLotDatas(ProductExcuteDto dto) {
		//保存产品历史记录lotHistory
		TwBasLot lot =  dto.getRowData();
		lot.setEqId(dto.getEqId());
		lot.setEqNo(dto.getEqNo());
		lot.setEqName(dto.getEqName()); 
		lot.setCompletedTime(new Date());
		saveLotHistory(lot);
		//更新产品状态，冻结或释放时，保存holdHistory
		updateLotInfo(dto);
	}
	
	@Override
	public void dealSpliceSelfnumber(ProductExcuteDto dto) {
		TwBasLot lot =  dto.getRowData();
		lot.setEqId(dto.getEqId());
		lot.setEqNo(dto.getEqNo());
		lot.setEqName(dto.getEqName()); 
		lot.setState("EMERGE");
		saveLotHistory(lot);
		saveSplice(dto);
		
	}
	
	// 当是合拼工位时自编号的保存并同时将自编号插入合拼中VIN号的数据中
	public void saveSplice(ProductExcuteDto dto) {
		TwBasLot lot = dto.getRowData();
		String selfNumber = dto.getSelfNumber();
		String vin = lot.getVin();
		Integer lotId = dto.getLotId();
		Integer updateSelfNumberByVin = 0;
		// updateSelfNumberByVin = twBasLotDao.updateSelfNumberByVin(selfNumber, vin,lotId);
		List<TwBasLot> list = new ArrayList<TwBasLot>();
		// 当自编号和vin号来自同一个item下时
		if (dto.getVinRowOrderItem().intValue() == lot.getOrderItemId().intValue()) {
			updateSelfNumberByVin = twBasLotDao.updateSelfNumberByVin(selfNumber, vin,lotId);
		} else {
			// 当自编号和vin号来自不同一个item下时
			List<TwBasLot> vinList = new ArrayList<TwBasLot>();
			List<TwBasLot> selfNumberList = new ArrayList<TwBasLot>();
			Assist assist = new Assist();
			assist.setRequires(Assist.andEq("order_item_id", dto.getVinRowOrderItem()));
			assist.setRequires(Assist.orEq("order_item_id", lot.getOrderItemId()));
			// 查询两个不同item的ID下的4条数据，并分类存储
			List<TwBasLot> selectTwBasLot = twBasLotDao.selectTwBasLot(assist);
			if (selectTwBasLot != null && selectTwBasLot.size() == 4 ) {
				for (TwBasLot twBasLot : selectTwBasLot) {
					if (twBasLot.getOrderItemId().intValue() == dto.getVinRowOrderItem().intValue()) {
						vinList.add(twBasLot);
						if (twBasLot.getVin() != null && twBasLot.getVin() != "") {
							twBasLot.setSelfNumber(selfNumber);
							list.add(twBasLot);
						}
					} else if (twBasLot.getOrderItemId().intValue() == lot.getOrderItemId().intValue()) {
						selfNumberList.add(twBasLot);
					}
				}
				// 将不同item下的自编号的item的id和队列编号进行置换位置
				loop: for (int i = 0; i < vinList.size(); i++) {
					for (int j = 0; j < selfNumberList.size(); j++) {
						if (vinList.get(i).getSelfNumber() != null && vinList.get(i).getSelfNumber() != "" && vinList.get(i).getVin() == null && selfNumberList.get(j).getSelfNumber() != null && selfNumberList.get(j).getSelfNumber() != "" && selfNumberList.get(j).getVin() == null) {
							Integer vinOrderItemId = vinList.get(i).getOrderItemId();
							String vinSequence = vinList.get(i).getSequence();
							vinList.get(i).setOrderItemId(selfNumberList.get(j).getOrderItemId());
							vinList.get(i).setSequence(selfNumberList.get(j).getSequence());
							selfNumberList.get(j).setState(MesConstant.LOT_STATE_MERGED);
							selfNumberList.get(j).setStatus(MesConstant.LOT_STATE_MERGED);
							selfNumberList.get(j).setOrderItemId(vinOrderItemId);
							selfNumberList.get(j).setSequence(vinSequence);
							list.add(vinList.get(i));
							list.add(selfNumberList.get(j));
							break loop;
						}
					}
				}
				
				
			}
		}
		if (list.size() != 0) {
			twBasLotDao.updateTwbasLotVinAndSelfnumberByid(list);
		}
		if (updateSelfNumberByVin > 0) {
			lot.setState(MesConstant.LOT_STATE_MERGED);
			lot.setStatus((MesConstant.LOT_STATE_MERGED));
			lot.setFinishedTime(new Date());
			this.updateTwBasLotById(lot);
		}
	}
	/*
	 * lot执行最后一个工位时更新工单的状态
	 * @param lot的数据  order 工单的数据
	 * 
	 * **/
	public boolean updateworkOrderAndItemStatus(TwBasLot lot,TwBasWorkOrder order) {
		boolean flag = true;
		if (lot.getOrderItemId()!= null && lot.getOrderNo()!=null & lot.getOrderNo()!="") {
			List<WorkOrderItem> workOrderItems = twBasWorkOrderDao.getWorkOrderItem(order.getOrderId());
			if (workOrderItems != null) {
				for (WorkOrderItem workOrderItem : workOrderItems) {
					if (workOrderItem.getId() == lot.getOrderItemId()) {
						workOrderItem.setOrderStatus(MesConstant.LOT_STATUS_FINISHED);
						workOrderItem.setLastUpdateTime(new Date());
						workOrderItem.setLastUpdateUser(SpringWebUtils.getRequestUser());
						twBasWorkOrderDao.updateOrderItemStatus(workOrderItem);
					}
					if (!workOrderItem.getOrderStatus().equals(MesConstant.LOT_STATUS_FINISHED)) {
						flag = false;
					}
				}
			}
		} else {
			flag = false;
		}
		return flag;
		
	}
	//更新产品状态，冻结或释放时，保存holdHistory
	private void updateLotInfo(ProductExcuteDto dto) {
		TwBasLot lot = dto.getRowData();
		String optType = dto.getOptType();
		Boolean consumFlag = dto.getConsumFlag();
		String currentUser = SpringWebUtils.getRequestUser();
		//查询lot对应的工单
		TwBasWorkOrder wo = twBasWorkOrderService.selectTwBasWorkOrderById(lot.getOrderId());
		Assist assist = new Assist();
		assist.setRequires(Assist.andEq("route", lot.getRoute()));
		assist.setRequires(Assist.andEq("operation_id", lot.getOperationId()));
		if(! MesConstant.LOT_STATUS_STARTED.equals(optType) && StringUtils.isNotBlank(lot.getCompletedReason())) {
			assist.setRequires(Assist.andEq("completion_reason", lot.getCompletedReason()));
		}
		List<TrBasRouteOperation> optList = trBasRouteOperationService.selectTrBasRouteOperation(assist);
		//更新产品当前状态
		if(optType.equals(MesConstant.LOT_STATUS_COMPLETED)) {//完成
	    		if(optList!=null&&optList.size()>0) {
	    			//查询下一道工序：当前工序不是最后一道工序则记录
	    			if(!"END".equals(optList.get(0).getOperationType())) {
	    				//修改lot的当前工序为下一道工序，下一道工序为，再“下一道工序”
	    				lot.setOperationId(optList.get(0).getNextOperationId());
		    			lot.setOperation(optList.get(0).getNextOperation());
		    			lot.setStatus(MesConstant.LOT_STATUS_WAITTING);
	    			}else {
	    				String operation = optList.get(0).getNextOperation();
	    				if(operation != null && !"".equals(operation)){
	    					
	    					if(lot.getIsLastOperation() == 1 && (lot.getCompletedReason() == null || "".equals(lot.getCompletedReason())) )
	    					{
	    						lot.setStatus(MesConstant.LOT_STATUS_FINISHED);//最后一站工序完成时，lot状态应该为已结束
	    	    				wo.setFinishedQty(wo.getFinishedQty()+1);
	    					}else {
	    						lot.setIsLastOperation(1);
		    					lot.setOperationId(optList.get(0).getNextOperationId());
				    			lot.setOperation(optList.get(0).getNextOperation());
				    			lot.setStatus(MesConstant.LOT_STATUS_WAITTING);
	    					}
	    				}
	    			}
	    		}
	    		if( (optList == null || optList.size() == 0) && lot.getIsLastOperation() == 1 ){
	    			lot.setStatus(MesConstant.LOT_STATUS_FINISHED);//最后一站工序完成时，lot状态应该为已结束
    				wo.setFinishedQty(wo.getFinishedQty()+1);
	    		}
	    		//判断是否有物料消耗，有：记录物料拉动
	    		System.out.println("consumFlag:"+consumFlag);
	    		if(consumFlag) {
	    			System.out.println("有物料消耗");
	    			final List<TeMesOutbound> outboundList = twBasLotConsumpationService.getConsumpationInfo(lot.getLotId(),optList.get(0).getOperationId());
	    			if(outboundList!=null&&outboundList.size()>0) {
	    				for(int i=0;i<outboundList.size();i++) {
	    					outboundList.get(i).setStatus("0");
	    					outboundList.get(i).setCreateTime(new Date());
	    					outboundList.get(i).setCreateUser(currentUser);
	    				}
	    				teMesOutboundService.insertTeMesOutboundByBatch(outboundList);
	    				//处理库存余量信息表
						try {
							   //20190825加的
						       twBasPackSkuQtyService.updateTwBasPackSkuQtyByProduce(outboundList);
						} catch (Exception e) {
							e.printStackTrace();
						}
	    			}
	    			// TODO FUNC fengxuanming 
	    			try {
	    				// 若扣库失败，不影响程序执行，数据仍被记录	    				
 	    				materialPullService.deductionMateriel(outboundList); 
				} catch (Exception e) {
					e.printStackTrace();
					throw new ServiceException(e.getMessage());
				}
	    		}
		}else if(optType.equals(MesConstant.LOT_STATUS_FINISHED)){ //结束
			lot.setStatus((MesConstant.LOT_STATUS_FINISHED));
			lot.setFinishedTime(new Date());
		}else if(optType.equals(MesConstant.LOT_STATUS_STARTED)){//开始
			//判断当前工位是否为开始工序，若是，则记录工单的开始时间及开始人
			
			if(StringUtils.isNotBlank(lot.getCompletedReason())) {
				if("fail".equals(lot.getCompletedReason())){
					assist = new Assist();
					assist.setRequires(Assist.andEq("completion_reason", "pass"));
					assist.setRequires(Assist.andEq("route", lot.getRoute()));
					assist.setRequires(Assist.andEq("operation_id", lot.getOperationId()));
					optList = trBasRouteOperationService.selectTrBasRouteOperation(assist);
				}
			}
			TrBasRouteOperation tro = null;
			for (TrBasRouteOperation trBasRouteOperation : optList) {
				if (trBasRouteOperation.getOperationType().equals("START")) {
					tro = trBasRouteOperation;
				}
			}
			if(((optList == null || optList.size() == 0) && lot.getIsLastOperation() == 1) || tro != null ) {
				if (tro != null && wo.getStartedTime() == null) {
					//工单开始时间
					wo.setStartedTime(new Date());
					//工单执行开始用户
					wo.setStartedUsername(currentUser);
				}
				//投入数量
				wo.setInputQty(wo.getInputQty()+1);
			}
			lot.setStartedTime(new Date());
			lot.setStatus(MesConstant.LOT_STATUS_STARTED);
			lot.setStartedUsername(currentUser);
		}else if(optType.equals(MesConstant.LOT_STATE_HOLD)) {//冻结
			//记录冻结历史
			saveLotHoldHistory(lot,MesConstant.LOT_STATE_HOLD);
			lot.setState(MesConstant.LOT_STATE_HOLD);
			if(wo.getRepairedQty()==null) {
				wo.setRepairedQty(0d);
			}
			//工单维修数量，默认维修人员确认需要维修时，Lot才会被冻结
			wo.setRepairedQty(wo.getRepairedQty()+1); 
		}else if(optType.equals(MesConstant.LOT_STATE_RELEASE)) {//释放
			//记录释放历史
			saveLotHoldHistory(lot,MesConstant.LOT_STATE_RELEASE);
			lot.setState(MesConstant.LOT_STATE_NORMAL);
		}else if(optType.equals(MesConstant.LOT_STATE_SCRAP)){ //报废
			lot.setState(MesConstant.LOT_STATE_SCRAP);
			//报废数量
			if(wo.getScrapedQty()==null) {
				wo.setScrapedQty(0d);
			}
			wo.setScrapedQty(wo.getScrapedQty()+1);
		}else if(optType.equals(MesConstant.LOT_STATUS_CLOSED)) { //关闭
			lot.setStatus(MesConstant.LOT_STATUS_CLOSED);
		}
		lot.setLastUpdateTime(new Date());
		lot.setLastUpdateUser(currentUser);
		this.updateTwBasLotById(lot);
		// 更新工单ITEM 返回是否将工单状态改为“完成”
		boolean updateworkOrderAndItemStatus = false;
		if (lot.getIsLastOperation() == 1 && optType.equals(MesConstant.LOT_STATUS_COMPLETED)&&(lot.getCompletedReason() == "" || lot.getCompletedReason() == null)) {
			lot.setFinishedTime(new Date());
			updateworkOrderAndItemStatus = updateworkOrderAndItemStatus(lot, wo);
		}
		
		if (updateworkOrderAndItemStatus) {
			if (wo.getFinishedTime() == null) {
				wo.setFinishedTime(new Date());
			}
			wo.setFinishedUsername(SpringWebUtils.getRequestUser());
			wo.setStatus(MesConstant.LOT_STATUS_FINISHED);
		}
		//更新工单
		twBasWorkOrderService.updateTwBasWorkOrderById(wo);
		//当产品最后一道工序完成时，打印产品条码
		if(lot.getStatus().equals(MesConstant.LOT_STATUS_FINISHED)) {
			printUpcCode(lot);
		}
	}
	//保存holdHistory
	private void saveLotHoldHistory(TwBasLot lot, String type) {
		String currentUser = SpringWebUtils.getRequestUser();
		String companyCode = SpringWebUtils.getRequestCompany();
		TwBasLotHoldHistory lotHoldHistory = new TwBasLotHoldHistory();
		lotHoldHistory.setLotId(lot.getLotId());
		lotHoldHistory.setLotName(lot.getLotName());
		if(type.equals(MesConstant.LOT_STATE_HOLD)) {
			lotHoldHistory.setHoldUsername(currentUser);
			lotHoldHistory.setHoldTime(new Date());
			//hold原因？
		}else if(type.equals(MesConstant.LOT_STATE_RELEASE)) {
			lotHoldHistory.setReleaseUsername(currentUser);
			lotHoldHistory.setReleaseTime(new Date());
			//release原因？
		}
		lotHoldHistory.setCreateTime(new Date());
		lotHoldHistory.setCreateUser(currentUser);
		lotHoldHistory.setMarkStatus(1);
		lotHoldHistory.setCompanyCode(companyCode);
		lotHoldHistory.setOptCounter(0);
		
	}
	
	//保存产品历史记录lotHistory
	private void saveLotHistory(TwBasLot lot) {
		String companyCode = SpringWebUtils.getRequestCompany();
		String remark = "";
		if(MesConstant.LOT_STATUS_WAITTING.equals(lot.getStatus())) {
			remark = "The last operation is completed,and the operation named"+lot.getOperation()+" is ";
		}
		//保存产品历史记录
		TwBasLotHistory lotHistory = new TwBasLotHistory();
		lotHistory.setLotId(lot.getLotId());
		lotHistory.setLotName(lot.getLotName());
		lotHistory.setLotQty(lot.getLotQty());
		lotHistory.setOrderId(lot.getOrderId());
		lotHistory.setOrderNo(lot.getOrderNo());
		lotHistory.setPartNoVersion(lot.getPartNoVersion());
		lotHistory.setBox(lot.getBox());
		lotHistory.setRoute(lot.getRoute());
		lotHistory.setProductionLine(lot.getProductionLine());
		lotHistory.setOperationId(lot.getOperationId());
		lotHistory.setOperation(lot.getOperation());
		lotHistory.setNextOperationId(lot.getNextOperationId());
		lotHistory.setNextOperation(lot.getNextOperation());
		lotHistory.setStationId(lot.getStationId());
		lotHistory.setStationName(lot.getStationName());
		lotHistory.setStartedUsername(lot.getStartedUsername());
		lotHistory.setStartedTime(lot.getStartedTime());
		lotHistory.setCompletedUsername(lot.getCompletedUsername());
		lotHistory.setCompletedTime(lot.getCompletedTime());
		lotHistory.setCompletedReason(lot.getCompletedReason());
		lotHistory.setStatus(lot.getStatus());
		if(MesConstant.LOT_STATUS_WAITTING.equals(lot.getStatus())) {
			lotHistory.setStatus(MesConstant.LOT_STATUS_COMPLETED+"-"+lot.getStatus());
		}
		lotHistory.setState(lot.getState());
		lotHistory.setComments(remark+lot.getStatus());
		lotHistory.setMarkStatus(lot.getMarkStatus());
		lotHistory.setCreateTime(new Date());
		lotHistory.setCreateUser(SpringWebUtils.getRequestUser());
		lotHistory.setLastUpdateUser(lot.getLastUpdateUser());
		lotHistory.setLastUpdateTime(lot.getLastUpdateTime());
		lotHistory.setCompanyCode(companyCode);
		lotHistory.setOptCounter(lot.getOptCounter());
		lotHistory.setEqId(lot.getEqId());
		lotHistory.setEqNo(lot.getEqNo());
		lotHistory.setEqName(lot.getEqName());
		int selectRepeatLotHistory = 0;
		if (lotHistory.getComments().equals("STARTED")) {
			// 查询是否有重复数据,若有则不让新增
			selectRepeatLotHistory = twBasLotHistoryDao.selectRepeatLotHistory(lotHistory);
		}
		if (selectRepeatLotHistory == 0) {
			twBasLotHistoryDao.insertTwBasLotHistory(lotHistory);
		}
		
	}
	
	//保存产品过程定义数据：包括物料消耗、检测、数据采集等
	private String saveOrUpdateProcessDef(ProductExcuteDto dto) {
		String errorMsg = "";
		Assist assist = new Assist();
		if(dto!=null) {
			TwBasLot lot = dto.getRowData();
			if(lot!=null) {
				assist.setRequires(Assist.andEq("lot_id", lot.getLotId()));
				assist.setRequires(Assist.andEq("operation_id", lot.getOperationId()));
			}
			//保存物料消耗数据
			if(dto.getConsumpation()!=null&&dto.getConsumpation().size()>0) {
				//判断该lot在当前工序下是否已记录物料消耗,是：批量更新零件序号，否：保存消耗记录
				List<TwBasLotConsumpation> consumpationsList = twBasLotConsumpationService.selectTwBasLotConsumpation(assist);
				if(consumpationsList!=null && consumpationsList.size()>0) {
					twBasLotConsumpationService.updateLotConsumpationsPartSnByBatch(consumpationsList,dto);
				}else {
					twBasLotConsumpationService.saveLotConsumpations(dto);
				}
				//校验sn号
//				String errorSnOfPartNoVersion = checkSn(dto.getConsumpation());
//				if(StringUtils.isNotBlank(errorSnOfPartNoVersion)) {
//					errorMsg = errorSnOfPartNoVersion;
//				}else {
//					if(consumpationsList!=null&&consumpationsList.size()>0) {
//						twBasLotConsumpationService.updateLotConsumpationsPartSnByBatch(consumpationsList,dto);
//					}else {
//						twBasLotConsumpationService.saveLotConsumpations(dto);
//					}
//				}
			}
			//保存测试项
			if(dto.getTesting()!=null&&dto.getTesting().size()>0) {
				List<TwBasLotTesting> testingList = twBasLotTestingService.selectTwBasLotTesting(assist);
				//判断该lot是否已记录检测值,是：批量更新检测值，否：保存检测值
				if(testingList!=null&&testingList.size()>0) {
					twBasLotTestingService.updateLotTestingValueByBatch(testingList,dto);
				}else {
					twBasLotTestingService.saveLotTesting(dto);
				}
			}
			//保存数据采集
			if(dto.getDci()!=null&&dto.getDci().size()>0) {
				//判断该lot是否已记录数据采集,是：批量更新采集数据，否：保存采集数据
				List<TwBasLotDataCollection> lotDciList = twBasLotDataCollectionService.selectTwBasLotDataCollection(assist);
				if(lotDciList!=null&&lotDciList.size()>0) {
					twBasLotDataCollectionService.updateLotDataCollectionValueByBatch(lotDciList,dto);
				}else {
					twBasLotDataCollectionService.saveLotDataCollection(dto);
				}
			}
			//保存维修数据
			if(dto.getRepair()!=null&&dto.getRepair().size()>0) {
				//判断该lot是否已记录维修数据，是：批量更新维修数据，否：保存维修数据
				List<TwBasLotRepair> lotRepList = twBasLotRepairDao.selectTwBasLotRepair(assist);
				if(lotRepList!=null&&lotRepList.size()>0) {
					twBasLotRepairService.updateLotRepairByBatch(lotRepList,dto);
				}else {
					twBasLotRepairService.saveLotRepair(dto);
				}
			}
		}
		return errorMsg;
	}
	
	//校验lot物料消耗中输入的序号
	private String checkSn(List<TrBasProductCfgBi> consumpation) {
		String errorSnOfPartNoVersion = "";
		for(TrBasProductCfgBi bi:consumpation ) {
			//验证关键件SN
			if(bi.getSnVerifyType()==1 || bi.getSnVerifyType()==2) {
				List<TmBasPartSn> partSnList = tmBasPartSnService.selectTmBasPartSn(
						new Assist().setRequires(
								Assist.andEq("part_sn", bi.getConsumedPartSn()),
								Assist.andEq("part_no_version", bi.getConsumedPartNoVersion())));
				if(partSnList!=null&&partSnList.size()>0) {
					if(partSnList.get(0).getIsConsumed()==1) {
						errorSnOfPartNoVersion+="零件号为"+bi.getConsumedPartNoVersion()+"的序号"+bi.getConsumedPartSn()+"已消耗,";
					}
				}else {
					errorSnOfPartNoVersion+="零件号为"+bi.getConsumedPartNoVersion()+"的序号"+bi.getConsumedPartSn()+"不存在,";
				}
			}
//			}else if(bi.getSnVerifyType()==2) {
//				//验证批次件
//				List<TwInvSkuLoctl> twInvSkuLoctlList = twInvSkuLoctlService.selectTwInvSkuLoctl(
//						new Assist().setRequires(
//								Assist.andEq("lot_no", bi.getConsumedPartSn())));
//				if(twInvSkuLoctlList==null || twInvSkuLoctlList.size()==0) {
//					errorSnOfPartNoVersion+="零件号为"+bi.getConsumedPartNoVersion()+"的批次号"+bi.getConsumedPartSn()+"不存在,";
//				}
//			}
		}
		return errorSnOfPartNoVersion;
	}
	
	//装箱
	@SuppressWarnings({ "unchecked", "rawtypes" })
	@Override
	public void packingBox(Map<Object, Object> map) {
		WorkOrderInfoDto infoDto = null;
		String currentUser =  SpringWebUtils.getRequestUser();
		try {
			//将map转换为对象
			 infoDto = (WorkOrderInfoDto) ObjectMapUtils.mapToObject((LinkedHashMap) map.get("stationInfo"), WorkOrderInfoDto.class);
		} catch (Exception e) {
			e.printStackTrace();
		}
		String[] lotNames = ((String) map.get("lotNames")).split(",");
		int count = 0;
		for(int i=0;i<lotNames.length;i++) {
			if(StringUtils.isNotBlank(lotNames[i])) {count++;}
		}
		if(infoDto!=null) {
			infoDto.setBoxNumber((String) map.get("packageSn"));
			infoDto.setPartNoVersion((String)map.get("partNoVersion"));
			infoDto.setLastUpdateTime(new Date());
			infoDto.setLastUpdateUser(currentUser);
			//更新lot中box信息
			twBasLotDao.updateLotsBoxByBatch(lotNames, infoDto);
			//补充包装表的其余信息
			updateBoxInfo(infoDto,count);
		}
	}
	
	//更新box信息
	private void updateBoxInfo(WorkOrderInfoDto infoDto,int actualBoxQty) {
		//获取工艺路径
		TrBasPdPlRoute pdpl = getRoute(infoDto.getLineId(),infoDto.getPartNoVersion());
		Assist boxAssist = new Assist();
		boxAssist.setRequires(Assist.andEq("package_sn", infoDto.getBoxNumber()));
		List<TmBasPackageSn> boxList = tmBasPackageSnService.selectTmBasPackageSn(boxAssist);
		if(boxList!=null&&boxList.size()>0) {
			TmBasPackageSn box = boxList.get(0);
			box.setLastUpdateTime(new Date());
			box.setLastUpdateUser(infoDto.getLastUpdateUser());
			box.setActualBoxQty(actualBoxQty);
			box.setIsUsed(1);
			box.setIsInbound(0);
			box.setRouteId(pdpl!=null?pdpl.getRouteId():null);
			box.setRouteName(pdpl!=null?pdpl.getRouteName():"");
			box.setOperationId(infoDto.getOperationId());
			box.setOperationName(infoDto.getOperationName());
			box.setLineName(infoDto.getLineName());
			box.setProductionLineId(infoDto.getLineId());
			box.setStationId(infoDto.getStationId());
			box.setStationName(infoDto.getStationName());
			tmBasPackageSnService.updateTmBasPackageSnById(box);
		}
	}

	//通过产线id及零件号获取工艺路径信息
	private TrBasPdPlRoute getRoute(Integer lineId, String partNoVersion) {
		TrBasPdPlRoute pdpl = null;
		Assist assist = new Assist();
		assist.setRequires(Assist.andEq("line_id",lineId));
		assist.setRequires(Assist.andEq("part_no_version", partNoVersion));
		List<TrBasPdPlRoute> pdList = trBasPdPlRouteService.selectTrBasPdPlRoute(assist);
		if(pdList!=null&&pdList.size()>0) {
			pdpl = pdList.get(0);
		}
		return pdpl;
	}
	@Override
	public List<ReportDto> getLineCapacity(String sDate, String eDate) {
		return twBasLotHistoryDao.getLineCapacity(sDate,eDate);
	}
	@Override
	public List<ReportDto> getStationCapacity(String sDate, String eDate) {
		return twBasLotHistoryDao.getStationCapacity(sDate,eDate);
	}
	@Override
	public List<ReportDto> getStGoodRate(String lineName, String sDate, String eDate) {
		return twBasLotHistoryDao.getStGoodRate(lineName,sDate, eDate);
	}
	@Override
	public List<ReportDto> getAbnormalInfo(ReportDto params) {
		SimpleDateFormat format0 = new SimpleDateFormat("yyyy.MM.dd");
		SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd");
		try {
			if(!StringUtil.isNullOrBlank(params.getsDate())){
					params.setsDate(format1.format(format0.parse(params.getsDate())));
			}
			if(!StringUtil.isNullOrBlank(params.geteDate())){
				params.seteDate(format1.format(format0.parse(params.geteDate())));
			}
		} catch (ParseException e) {
			e.printStackTrace();
		}

		return twBasLotRepairDao.getAbnormalInfo(params);
	}
	@Override
	public void doWarehousing(WorkOrderInfoDto dto) {
		//获取当前的用户名
		String currentUser = SpringWebUtils.getRequestUser();
		//获取当前用户的企业代码
		String companyCode = SpringWebUtils.getRequestCompany();
		TeProductInbound inbound = teProductInboundService.getInboundPackInfo(dto.getBoxNumber());
		//若参数工单号存在，入库来源是产品包装，则直接赋值；若参数不存在，入库来源是包装序列号页面，则需要查询工单号
		if(StringUtils.isNotBlank(dto.getOrderNumber())) {
			inbound.setPartNoVersion(dto.getPartNoVersion());
			inbound.setOrderNo(dto.getOrderNumber());
			inbound.setSoNo(dto.getSalesOrder());
		}else {
			//同一个包装的工单相同，故通过包装序号查询LOT信息
			Assist assist = new Assist();
			assist.setRequires(Assist.andEq("box", dto.getBoxNumber()));
			List<TwBasLot> lotList = this.selectTwBasLot(assist);
			if(lotList!=null&&lotList.size()>0) {
				TwBasLot lot = lotList.get(0);
				TwBasWorkOrder wo = twBasWorkOrderService.selectTwBasWorkOrderById(lot.getOrderId());
				inbound.setPartNoVersion(wo.getPartNoVersion());
				inbound.setOrderNo(wo.getOrderNumber());
				inbound.setSoNo(wo.getSalesOrder());
			}
		}
		inbound.setPackNum(1);
		inbound.setStatus("0");
		inbound.setCreateTime(new Date());
		inbound.setCreateUser(currentUser);
		inbound.setCompanyCode(companyCode);
		inbound.setMarkStatus(1);
		teProductInboundService.insertTeProductInbound(inbound);
		//更新物料包装中的是否入库状态为待入库
		tmBasPackageSnService.updateIsInbound(dto.getBoxNumber());
		//打印箱卡
		printBoxCard(inbound);
	}
	
	//打印箱卡
	@SuppressWarnings("unchecked")
	private void printBoxCard(TeProductInbound inbound) {
		//箱卡模板地址
		String filePath = "jrxml/boxCard.jasper";
		//填充参数，ireport中通过$P{key_name}获取
		Map<String,Object> parameters = new HashMap<String,Object>(); 
		if(inbound!=null) {
			parameters.put("BOX_NO", inbound.getPackSerialNo());
			parameters.put("QTY", inbound.getPartQty());
			parameters.put("PACK_DATE",DateUtils.format(inbound.getCreateTime(), DateUtils.FORMAT_DATE_YYYY_MM_DD));//打包时间和入库时间是否一致？
			parameters.put("PART_NAME",inbound.getPartNoVersion().split("_")[0]);//查询零件名称
			parameters.put("VENDOR", "苏州益发特科技有限公司上海分公司");
			parameters.put("ADDR", "上海市徐汇区钦州北路188号");
		}
		@SuppressWarnings("rawtypes")
		PrintCardUtil util = new PrintCardUtil<>(null);
		util.iReportWebPrint(parameters, filePath);
		
	}
	
	@Override
	public void printFlowCard(TwBasLot lot) {
		//工艺流程卡模板文件地址
		String filePath = "jrxml/flowCard.jasper";
		//获取要显示的数据，通过$F{key_name}获取
		List<LabelPrintDto> reportList = twBasLotDao.getFlowCardData(lot); 
		//填充参数，ireport中通过$P{key_name}获取
		Map<String,Object> parameters = new HashMap<String,Object>(); 
		if(reportList!=null&&reportList.size()>0) {
			parameters.put("lotName",reportList.get(0).getLotName());
			parameters.put("partNoVersion", reportList.get(0).getPartNoVersion());
			parameters.put("routeName", reportList.get(0).getRouteName());
			parameters.put("partNameC", reportList.get(0).getPartNameC());
		}
		PrintCardUtil<LabelPrintDto> util = new PrintCardUtil<>(reportList);
		util.iReportWebPrint(parameters, filePath);
	}	
	
	//打印产品条码
	@SuppressWarnings("unchecked")
	private void printUpcCode(TwBasLot lot) {
		//箱卡模板地址
		String filePath = "jrxml/upcCode.jasper";
		//填充参数，ireport中通过$P{key_name}获取
		Map<String,Object> parameters = new HashMap<String,Object>(); 
		if(lot!=null) {
			parameters.put("LOT_NAME", lot.getLotName());
			parameters.put("PART_NAME", "轴承");//查询产品名称
			parameters.put("VENDOR", "苏州益发特科技有限公司上海分公司");
			parameters.put("ADDR", "上海市徐汇区钦州北路188号");
		}
		@SuppressWarnings("rawtypes")
		PrintCardUtil util = new PrintCardUtil<>(null);
		util.iReportWebPrint(parameters, filePath);
	}
	
	// 打印翻包标签
	@SuppressWarnings("unchecked")
	@Override
	public void printTurnOverCard(List<TwPacktranTaskDetail> twPacktranTaskDetails) {
		//翻包标签模板地址
		String filePath = "jrxml/turnoverCard.jasper";
		//填充参数，ireport中通过$P{key_name}获取
		Map<String,Object> parameters = new HashMap<String,Object>(); 
		if(twPacktranTaskDetails!=null&&twPacktranTaskDetails.size()>0) {
			for(TwPacktranTaskDetail ptd: twPacktranTaskDetails) {
				parameters.put("partPackedSn", ptd.getPartPackSerial());
				parameters.put("qty", ptd.getActNboundQty() );
				parameters.put("datePacked", DateUtils.format(new Date(), DateUtils.FORMAT_DATE_YYYY_MM_DD) );
				parameters.put("partNameCn", ptd.getPartNameC());
				parameters.put("partNameEn", ptd.getPartNameC());
				parameters.put("partNoVersion", ptd.getPartNoVersion());
				parameters.put("plantName", VENDOR);
				parameters.put("plantAddr", ADDR);
				@SuppressWarnings("rawtypes")
				PrintCardUtil util = new PrintCardUtil<>(null);
				util.iReportWebPrint(parameters, filePath);
			}
		}
	}
	
	// 打印质检标签
	@SuppressWarnings("unchecked")
	@Override
	public void printQualityTestingCard(TwQualityTaskDetail twQualityTaskDetail) {
		String filePath = "jrxml/quantityTestingCard.jasper";
		Map<String,Object> parameters = new HashMap<String,Object>(); 
		List<TmBasPart> partList = tmBasPartService.selectTmBasPart(new Assist().setRequires(Assist.andEq("part_no_version", twQualityTaskDetail.getPartNoVersion())));
		if(twQualityTaskDetail!=null) {
			parameters.put("partPackedSn", twQualityTaskDetail.getPartPackSerial());
			parameters.put("qty", twQualityTaskDetail.getActNboundQty() );
			parameters.put("datePacked", DateUtils.format(new Date(), DateUtils.FORMAT_DATE_YYYY_MM_DD) );
			parameters.put("partNameCn", twQualityTaskDetail.getPartNameC());
			parameters.put("partNameEn", partList!=null&&partList.size()>0?partList.get(0).getPartNameE():"");
			parameters.put("partNoVersion", twQualityTaskDetail.getPartNoVersion());
			parameters.put("plantName", VENDOR);
			parameters.put("plantAddr", ADDR);
			@SuppressWarnings("rawtypes")
			PrintCardUtil util = new PrintCardUtil<>(null);
			util.iReportWebPrint(parameters, filePath);
		}
	}
	
	// 打印上架清单
	@Override
	public void printGroundingList(List<TwInbTaskDetail> dbListTwInbTaskDetail) {
		String filePath = "jrxml/putawayTaskList.jasper";
		List<LabelPrintDto> dtoList = new ArrayList<LabelPrintDto>();
		//填充参数，ireport中通过$P{key_name}获取
		Map<String,Object> parameters = new HashMap<String,Object>(); 
		if(dbListTwInbTaskDetail!=null&&dbListTwInbTaskDetail.size()>0) {
			//查询所有供应商编号对应的供应商名称
			String supplNos = "";
			for(TwInbTaskDetail inb:dbListTwInbTaskDetail) {
				supplNos+="'"+inb.getSupplNo()+"',";
			}
			Map<String,String> supplMap = getSupplMap(StringUtils.isNotBlank(supplNos)?supplNos.substring(0, supplNos.length()-1):"");
			//遍历赋值需要循环的对象
			int i=1;
			for(TwInbTaskDetail inb:dbListTwInbTaskDetail) {
				LabelPrintDto dto = new LabelPrintDto();
				dto.setLineNo(String.valueOf(i));
				dto.setPartNoVersion(inb.getPartNoVersion());
				dto.setPartNameC(inb.getPartNamec());
				dto.setSupplNo(inb.getSupplNo());
				dto.setSupplName(supplMap.containsKey(inb.getSupplNo())?supplMap.get(inb.getSupplNo()):"");
				dto.setPreNboundQty(inb.getPreNboundQty());
				dto.setPreTmBasStorageNo(inb.getPreTmBasStorageNo());
				dto.setInboundPackNo(inb.getInboundPackNo());
				dto.setPartPackSerial(inb.getPartPackSerial());
				dto.setInbSerialNo(inb.getInbSerialNo());
				dto.setLotNo(inb.getLotNo());
				dtoList.add(dto);
				i++;
			}
			parameters.put("putawayOrderNo", dbListTwInbTaskDetail.get(0).getInboundAllocNo());
			parameters.put("asnNo", dbListTwInbTaskDetail.get(0).getAsnSheetNo());
			parameters.put("putawayDate", DateUtils.format(new Date(), DateUtils.FORMAT_DATE_YYYY_MM_DD));
			parameters.put("printDate", DateUtils.format(new Date(), DateUtils.FORMAT_DATE_YYYY_MM_DD));
		}
		PrintCardUtil<LabelPrintDto> util = new PrintCardUtil<>(dtoList);
		util.iReportWebPrint(parameters, filePath);
	}
	
	//查询供应商编号对应的供应商名称
	private Map<String, String> getSupplMap(String supplNos) {
		Map<String,String> supplMap = new HashMap<String,String>();
		List<TmBasSuppl> supplList = tmBasSupplService.selectTmBasSuppl(new Assist().setRequires(
				Assist.customRequire("suppl_no in ( ",supplNos, ")")));
		if(supplList!=null && supplList.size()>0) {
			for(TmBasSuppl suppl:supplList) {
				supplMap.put(suppl.getSupplNo(), suppl.getSupplNamec());
			}
		}
		return supplMap;
	}
	//打印拣货任务单
	@Override
	public void printPickCard(List<TwOutbTaskDetail> listTwOutbTaskDetail,String custsheetNo) {
		String filePath = "jrxml/putawayTaskList.jasper";
		List<LabelPrintDto> dtoList = new ArrayList<LabelPrintDto>();
		Map<String,Object> parameters = new HashMap<String,Object>(); 
		//获取对象list
		if(listTwOutbTaskDetail!=null&&listTwOutbTaskDetail.size()>0) {
			//获取供应商编码对应的供应商名称
			String supplNos = "";
			String locIds = "";
			for(TwOutbTaskDetail out:listTwOutbTaskDetail) {
				supplNos+="'"+out.getSupplNo()+"',";
				locIds+="'"+out.getActTmBasStorageId()+"',";
			}
			Map<String,String> supplMap = getSupplMap(StringUtils.isNotBlank(supplNos)?supplNos.substring(0, supplNos.length()-1):"");
			Map<Integer,String> locMap = getLocMap(StringUtils.isNotBlank(locIds)?supplNos.substring(0, supplNos.length()-1):"");
			int i=0;
			for(TwOutbTaskDetail outb: listTwOutbTaskDetail) {
				LabelPrintDto dto = new LabelPrintDto();
				dto.setLineNo(String.valueOf(i));
				dto.setPartNoVersion(outb.getPartNoVersion());
				dto.setPartNameC(outb.getPartNamec());
				dto.setSupplNo(outb.getSupplNo());
				dto.setSupplName(supplMap.containsKey(outb.getSupplNo())?supplMap.get(outb.getSupplNo()):"");
				dto.setAllocQty(outb.getAllocQty());
				dto.setAllocPack(outb.getAllocPack());
				dto.setInbSerialNo(outb.getInbSerialNo());
				dto.setPreLoc(locMap.get(outb.getActTmBasStorageId()));
				dto.setLotNo(outb.getLotNo());
			}
			parameters.put("pickTaskNo", listTwOutbTaskDetail.get(0).getPickAllocNo());
			parameters.put("outBoundNo", listTwOutbTaskDetail.get(0).getSoSheetNo());
			parameters.put("customOrderNo",custsheetNo);
			parameters.put("pickDate",DateUtils.format(new Date(), DateUtils.FORMAT_DATE_YYYY_MM_DD));
			parameters.put("printDate",DateUtils.format(new Date(), DateUtils.FORMAT_DATE_YYYY_MM_DD) );
		}
		PrintCardUtil<LabelPrintDto> util = new PrintCardUtil<>(dtoList);
		util.iReportWebPrint(parameters, filePath);
	}
	//查询库位id对应的库位编号
	private Map<Integer, String> getLocMap(String locIds) {
		Map<Integer,String> map = new HashMap<Integer,String>();
		List<TmBasLoc> locList = tmBasLocService.selectTmBasLoc(new Assist().setRequires(
				Assist.customRequire("tm_bas_loc_id in (", locIds, ")")));
		if(locList!=null&&locList.size()>0) {
			for(TmBasLoc loc: locList) {
				map.put(loc.getTmBasLocId(), loc.getStorageNo());
			}
		}
		return map;
	}
	@Override
	public Map<String, Object> selectTwBasLotByName(String lotName) {
		TwBasLot lot = twBasLotDao.selectTwBasLotByname(lotName);
		Map<String, Object> info = twBasWorkOrderService.getWorkOrderInfo(lot.getOrderNo());
		info.put("lot", lot);
		return info;
	}
	@Override
	public TwBasLot getDefFromLotName(String lotName) {
		
		return twBasLotDao.getDefFromLotName(lotName);
	}
	@Override
	public boolean dealRowDate(TwBasLot lot) {
		Assist assist = new Assist();
		assist.setRequires(Assist.andEq("lot_id", lot.getLotId()));
		assist.setRequires(Assist.andEq("operation_id", lot.getOperationId()));
		List<TwBasLotDataCollection> lotDciList = twBasLotDataCollectionService.selectTwBasLotDataCollection(assist);
		boolean flag =false;
		if(lotDciList.size()==1) {
			flag=true;
		}
		return flag;
	}
	@Override
	public boolean closeLot(Integer lotID) {
		//String state;//lot状态：normal，hold，scrap
	    //String status;//运行状态:created,started,completed,finished,closed
		
		String requestUser = SpringWebUtils.getRequestUser();
		TwBasLot lot = selectTwBasLotById(lotID);
		if(lot !=null) {
			int closeLotsByID = twBasLotDao.closeLotsByID(MesConstant.LOT_STATUS_CLOSED, requestUser, new Date(), lotID);
			if(closeLotsByID==1) {
				return true;
			}else {
				return false;
			}
		}
		return true;
	}
	@Override
	public boolean scrapLot(Integer lotID) {
		TwBasLot lot = selectTwBasLotById(lotID);
		String requestUser = SpringWebUtils.getRequestUser();
		if(lot !=null) {
			int closeLotsByID = twBasLotDao.scrapLotsByID("closed", "scrap", requestUser, new Date(), lotID);
			if(closeLotsByID==1) {
				return true;
			}else {
				return false;
			}
		}
		return true;
	}
	
	@Override
	public ResultBean validateVIN(String bsn, String vin) {
		
		ResultBean resultBean = new ResultBean(true, null);
		
		String vins = vin.trim();
		if (vins.length() == 17) {
			// Boolean checkVin = vinRuleService.checkVin(selectTwBasLot.get(0).getPartNoVersion(), vin);
			String vinPrefix = vins.substring(0, 8);
			String vis = vins.substring(9);
			String checkNo = vinRuleService.getCheckNo(vinPrefix, vis);
			if (! vins.substring(8, 9).equals(checkNo)) {
				resultBean.setSuccess(false);
				resultBean.setMessage("输入的VIN号不正确！");
				return resultBean;
			}
		} else {
			resultBean.setSuccess(false);
			resultBean.setMessage("输入的VIN号长度不足十七位!");
			return resultBean;
		}
		
		boolean cancelReuse = false ;
		boolean alreadyBind = false;
		
		Assist assist = new Assist();
		assist.setRequires(Assist.andEq("vin",vin));
		List<TwBasLot> selectTwBasLot = twBasLotDao.selectTwBasLot(assist);
		if (selectTwBasLot.size() >0) {
			for (TwBasLot twBasLot : selectTwBasLot) {
				if ("CANCELLED".equals(twBasLot.getStatus())) {
					cancelReuse = true;
				}
				else {
					alreadyBind = true;
				}
			}
		}
		
		if (cancelReuse) {
			resultBean.setSuccess(true);
			resultBean.setMessage("该VIN号/"+vin+"/为已取消订单绑定，是否确认再次绑定？");
		}else if(alreadyBind){
			resultBean.setSuccess(false);
			resultBean.setMessage("该VIN号/"+vin+"/已绑定过!");
		}else {
			resultBean.setObject(vin);
		}
		return resultBean;
	}
	@Override
	public ResultBean generateVin(String bsn, String vin) {
		ResultBean resultBean = new ResultBean(true,null);
		twBasLotDao.generateVin(bsn, vin);
		return resultBean;
	}
	
	@Override
	public ResultBean searchLotByselfNumber(Map<String,Object> map) {
		String selfNumber = (String)map.get("selfNumber");
		String orderNo = (String)map.get("orderNo");
		Integer operationId = Integer.parseInt(map.get("operationId").toString());
		// String operationId = (String)map.get("operationId");
		ResultBean resultBean = new ResultBean();
		if (selfNumber == "" || selfNumber == null) {
			resultBean.setSuccess(false);
			resultBean.setMessage("请输入一个自编号");
		} else {
			Assist assist = new Assist();
			assist.setRequires(Assist.andEq("self_number", selfNumber));
			assist.setRequires(Assist.andEq("order_no", orderNo));
			assist.setRequires(Assist.andEq("operation_id", operationId));
			List<TwBasLot> selectTwBasLot = twBasLotDao.selectTwBasLot(assist);
			if (selectTwBasLot != null && selectTwBasLot.size() == 1) {
				resultBean.setSuccess(true);
				resultBean.setObject(selectTwBasLot);
			} else {
				resultBean.setSuccess(false);
				if (selectTwBasLot.size() == 0 || selectTwBasLot == null) {
					resultBean.setMessage("在当前工位工单中无法查询到此自编号!");
				} else {
					resultBean.setMessage("查询出错");
				}
			}
		}
		return resultBean;
	}
	@Override
	public void dealSpliceLotDatas(TwBasLot twBasLot) {
		twBasLot.setFinishedTime(new Date());
		twBasLot.setCreateTime(new Date());
		twBasLot.setCreateUser(SpringWebUtils.getRequestUser());
		twBasLot.setLastUpdateTime(new Date());
		twBasLot.setLastUpdateUser(SpringWebUtils.getRequestUser());
		twBasLotDao.addLotSpliceDate(twBasLot);
		
	}
	@Override
	public boolean valliVinExist(Map<String, Object> map) {
		List<String> valliVinExist = twBasLotDao.valliVinExist(map);
		if (valliVinExist.size() == 0) {
			return false;
		} else {
			return true;
		}
	}
	@Override
	public ResultBean selelotByctselfNumberAndlotName(String lotName, String selfNumber) {
		ResultBean resultBean = new ResultBean();
		TwBasLot lot = twBasLotDao.selectlotBySelfNumberLotname(selfNumber, lotName);
		if (lot != null) {
			resultBean.setSuccess(true);
			resultBean.setObject(lot);
		} else {
			resultBean.setSuccess(false);
		}
		return resultBean;
	}
	@Override
	public ResultBean freezeLot(List<TwBasLot> twBasLot) {
		ResultBean resultBean = new ResultBean(true,"'");
		if(twBasLot != null && twBasLot.size()>0) {
			for(TwBasLot data:twBasLot) {
				data.setLastUpdateTime(new Date());
				data.setLastUpdateUser(SpringWebUtils.getRequestUser());
				data.setState(MesConstant.LOT_STATE_HOLD);
				data.setCreateTime(new Date());
				data.setCreateUser(SpringWebUtils.getRequestUser());
				data.setCompanyCode(SpringWebUtils.getRequestCompany());
				data.setOperationUser(SpringWebUtils.getRequestUser());
				data.setOperationTime(new Date());
				data.setActionFlag("冻结");
			}
			twBasLotDao.updateStateByLot(twBasLot);
			//保存冻结时记录
			twBasLotDao.insertFreezeHistory(twBasLot);
			this.updateWorkOrderStatus(MesConstant.WORK_ORDER_FREEZE, MesConstant.WORK_ORDER_ITEM_FREEZE,
					MesConstant.LOT_STATE_HOLD, twBasLot);
			resultBean.setSuccess(true);
			resultBean.setMessage("冻结成功!");
		} else {
			resultBean.setSuccess(false);
			resultBean.setMessage("请选择车辆信息！");
		}
		return resultBean;
	}
	
	@Override
	public ResultBean scrapLotState(List<TwBasLot> twBasLot) {
		ResultBean resultBean = new ResultBean(true,"'");
		if(twBasLot != null && twBasLot.size()>0) {
			for(TwBasLot data:twBasLot) {
				data.setLastUpdateTime(new Date());
				data.setLastUpdateUser(SpringWebUtils.getRequestUser());
				data.setState(MesConstant.LOT_STATE_NORMAL);
				data.setCreateTime(new Date());
				data.setCreateUser(SpringWebUtils.getRequestUser());
				data.setCompanyCode(SpringWebUtils.getRequestCompany());
				data.setOperationUser(SpringWebUtils.getRequestUser());
				data.setOperationTime(new Date());
				data.setActionFlag("解冻");
			}
			twBasLotDao.updateStateByLot(twBasLot);
			//保存解冻时记录
			twBasLotDao.insertFreezeHistory(twBasLot);
			// "unfreeze"标识解冻操作
		    this.updateWorkOrderStatus("unfreeze", "unfreeze", MesConstant.LOT_STATE_NORMAL, twBasLot);
			resultBean.setSuccess(true);
			resultBean.setMessage("解冻成功!");
		} else {
			resultBean.setSuccess(false);
			resultBean.setMessage("请选择车辆信息！");
		}
		return resultBean;
	}
	
	@Override
	public ResultBean updateWorkOrderStatus(String orderStatus, String orderItemStatus, String lotStatus,
			List<TwBasLot> twBasLot) {
		ResultBean resultBean = new ResultBean(true, "'");
		// 货车集合
		List<TwBasLot> truckList = new ArrayList<TwBasLot>();
		// 客车、专用车集合
		List<TwBasLot> otherCarList = new ArrayList<TwBasLot>();
		if (twBasLot != null && twBasLot.size() > 0) {
			for (TwBasLot data : twBasLot) {
				if ("A".equals(data.getLotType())) {
					truckList.add(data);
				} else {
					otherCarList.add(data);
				}
			}
			if (truckList != null && truckList.size() > 0) {
				for (TwBasLot data : truckList) {
					data.setLastUpdateTime(new Date());
					data.setLastUpdateUser(SpringWebUtils.getRequestUser());
					data.setState(orderStatus);// 暂时用于接收order状态
					data.setStatus(orderItemStatus);// 用于接收OrderItem状态
					// 总数量
					Integer qty = twBasLotDao.selectOrderQtyByOrderId(data.getOrderId());
					// 查询工单item数量
					TwBasLot basLot = new TwBasLot();

					basLot.setOrderItemId(data.getOrderItemId());
					Integer orderItemQty = twBasLotDao.selectOrderItemQty(basLot);
					if (lotStatus.equals(MesConstant.LOT_STATE_SCRAP)) {
						basLot.setState(MesConstant.LOT_STATE_SCRAP);
						basLot.setStatus(MesConstant.LOT_STATUS_CLOSED);
					} else if (lotStatus.equals(MesConstant.LOT_STATE_HOLD)) {
						basLot.setState(MesConstant.LOT_STATE_HOLD);
					} else if (lotStatus.equals(MesConstant.LOT_STATE_NORMAL)) {
						basLot.setState(MesConstant.LOT_STATE_NORMAL);
					} else {
						basLot.setStatus(MesConstant.LOT_STATUS_CLOSED);
					}
					Integer orderItemSatusQty = twBasLotDao.selectOrderItemQty(basLot);
					if (orderItemQty.equals(orderItemSatusQty) && orderStatus.equals(MesConstant.WORK_ORDER_FREEZE)) {
						String orderItemFreezeStatus = twBasLotDao.selectOrderItemStaus(data.getOrderItemId());
						data.setFreezeStatus(orderItemFreezeStatus);
						twBasLotDao.updateWorkOrderItemStatus(data);
					} else if (orderItemQty.equals(orderItemSatusQty) && orderStatus.equals("unfreeze")) {
						String freezeOrderItemStatus = twBasLotDao.selectFreezeStatus(data.getOrderItemId());
						data.setStatus(freezeOrderItemStatus);
						twBasLotDao.updateWorkOrderItemStatus(data);
					} else if (orderItemQty.equals(orderItemSatusQty)) {
						twBasLotDao.updateWorkOrderItemStatus(data);
					}
					// 查询order状态下item数量
					Integer orderStatusQty;
					if(orderStatus.equals("unfreeze")) {
						orderStatusQty = twBasLotDao.selectUnfreezeOrderStatusQtyByOrderId(data.getOrderId(),
								MesConstant.WORK_ORDER_ITEM_FREEZE);
					}else {
						orderStatusQty = twBasLotDao.selectOrderStatusQtyByOrderId(data.getOrderId(),
								orderItemStatus);
					}
					if (qty.equals(orderStatusQty) && orderStatus.equals(MesConstant.WORK_ORDER_FREEZE)) {
						String orderFreezeStatus = twBasLotDao.selectOrderStaus(data.getOrderId());
						data.setFreezeStatus(orderFreezeStatus);
						twBasLotDao.updateWorkOrderStatus(data);
					} else if (qty.equals(orderStatusQty) && orderStatus.equals("unfreeze")) {
						String freezeOrderStatus = twBasLotDao.selectFreezeStatusByOrderId(data.getOrderId());
						data.setState(freezeOrderStatus);
						twBasLotDao.updateWorkOrderStatus(data);
					} else if (qty.equals(orderStatusQty)) {
						twBasLotDao.updateWorkOrderStatus(data);
					}
				}
			}
			if (otherCarList != null && otherCarList.size() > 0) {
				for (TwBasLot data : otherCarList) {
					data.setLastUpdateTime(new Date());
					data.setLastUpdateUser(SpringWebUtils.getRequestUser());
					data.setState(orderStatus);// 暂时用于接收order状态
					data.setStatus(orderItemStatus);// 用于接收OrderItem状态
					// 总数量
					Integer qty = twBasLotDao.selectOrderQtyByOrderId(data.getOrderId());
					if(orderStatus.equals(MesConstant.WORK_ORDER_FREEZE)) {
						String orderItemFreezeStatus = twBasLotDao.selectOrderItemStaus(data.getOrderItemId());
						data.setFreezeStatus(orderItemFreezeStatus);
						twBasLotDao.updateWorkOrderItemStatus(data);
					} else if (orderStatus.equals("unfreeze")) {
						String freezeOrderItemStatus = twBasLotDao.selectFreezeStatus(data.getOrderItemId());
						data.setStatus(freezeOrderItemStatus);
						twBasLotDao.updateWorkOrderItemStatus(data);
					} else {
						twBasLotDao.updateWorkOrderItemStatus(data);
					}
					// 查询order状态下item数量
					Integer orderStatusQty;
					if(orderStatus.equals("unfreeze")) {
						orderStatusQty = twBasLotDao.selectUnfreezeOrderStatusQtyByOrderId(data.getOrderId(),
								MesConstant.WORK_ORDER_ITEM_FREEZE);
					}else {
						orderStatusQty = twBasLotDao.selectOrderStatusQtyByOrderId(data.getOrderId(),
								orderItemStatus);
					}
					if (qty.equals(orderStatusQty)&& orderStatus.equals(MesConstant.WORK_ORDER_FREEZE)) {
						String orderFreezeStatus = twBasLotDao.selectOrderStaus(data.getOrderId());
						data.setFreezeStatus(orderFreezeStatus);
						twBasLotDao.updateWorkOrderStatus(data);
					} else if (qty.equals(orderStatusQty) && orderStatus.equals("unfreeze")) {
						String freezeOrderStatus = twBasLotDao.selectFreezeStatusByOrderId(data.getOrderId());
						data.setState(freezeOrderStatus);
						twBasLotDao.updateWorkOrderStatus(data);
					} else if (qty.equals(orderStatusQty)) {
						twBasLotDao.updateWorkOrderStatus(data);
					}
				}
			}
		}
		return resultBean;
	}
}